import Sortable, { type SortableOptions } from 'sortablejs'

export function useSortable(
  container: Ref<HTMLElement | undefined>,
  list: Ref,
  options?: SortableOptions
) {
  const instance = shallowRef()

  onMounted(() => {
    instance.value = Sortable.create(container.value!, {
      ...options,
      onUpdate: e => {
        options?.onUpdate?.(e)
        const oldValue = list.value[e.oldIndex!]
        list.value.splice(e.oldIndex!, 1)
        list.value.splice(e.newIndex!, 0, oldValue)
      }
    })

    onUnmounted(() => {
      instance.value.destroy()
    })
  })

  function destroy() {
    instance.value.destroy()
  }

  return {
    instance,
    destroy
  }
}
